package com.xjc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.CollageAdminRelations;
import com.xjc.business.entity.domain.CollegeAdmins;
import com.xjc.business.entity.domain.SchoolCollageAdminRelations;
import com.xjc.business.entity.po.coladmin.ColAdminLoginPo;
import com.xjc.business.entity.po.schadmin.PersonPo;
import com.xjc.business.entity.vo.PageVo;
import com.xjc.business.entity.vo.coladmin.ColAdminLoginVo;
import com.xjc.business.entity.vo.schadmin.CollegeRestAdminVo;
import com.xjc.business.entity.vo.schadmin.PersonVo;
import com.xjc.business.service.CollageAdminRelationsService;
import com.xjc.business.service.CollegeAdminsService;
import com.xjc.business.mapper.CollegeAdminsMapper;
import com.xjc.business.service.SchoolCollageAdminRelationsService;
import com.xjc.business.service.SchoolSetsService;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.BcryptUtil;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author root
* @description 针对表【college_admins(学院管理员表)】的数据库操作Service实现
* @createDate 2025-01-25 10:24:31
*/
@Service
public class CollegeAdminsServiceImpl extends ServiceImpl<CollegeAdminsMapper, CollegeAdmins>
    implements CollegeAdminsService {

    @Autowired
    @Lazy
    SchoolCollageAdminRelationsService schoolCollageAdminRelationsService;

    @Autowired
    @Lazy
    CollageAdminRelationsService collageAdminRelationsService;

    @Autowired
    @Lazy
    SchoolSetsService schoolSetsService;

    /**
     * 分页查询人员信息
     *
     * @param pageSize      每页显示条数
     * @param currentPage   当前页码
     * @param adminUserName 用户名
     * @param adminNickName 昵称
     * @param schoolId
     * @return 信息
     */
    @Override
    public Result<PageVo<PersonVo>> getCollegeAdminPage(Integer pageSize, Integer currentPage, String adminUserName, String adminNickName, Integer schoolId) {

        LambdaQueryWrapper<SchoolCollageAdminRelations> schoolCollageAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolCollageAdminRelationsLambdaQueryWrapper.eq(SchoolCollageAdminRelations::getSchId, schoolId);

        List<SchoolCollageAdminRelations> schoolCollageAdminRelationsList = schoolCollageAdminRelationsService.list(schoolCollageAdminRelationsLambdaQueryWrapper);
        List<Integer> collectIdList = schoolCollageAdminRelationsList.stream().map(SchoolCollageAdminRelations::getColAdminId).collect(Collectors.toList());

        PageVo<PersonVo> pageVo = new PageVo<>();

        if(collectIdList.isEmpty()){
            return Result.okWithData(pageVo);
        }

        LambdaQueryWrapper<CollegeAdmins> collegeAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        collegeAdminsLambdaQueryWrapper.like(!adminUserName.isEmpty(), CollegeAdmins::getUsername, adminUserName);
        collegeAdminsLambdaQueryWrapper.like(!adminNickName.isEmpty(), CollegeAdmins::getNickname, adminNickName);
        collegeAdminsLambdaQueryWrapper.in(CollegeAdmins::getId, collectIdList);

        Page<CollegeAdmins> collegeAdminsPage = new Page<>(currentPage, pageSize);
        page(collegeAdminsPage, collegeAdminsLambdaQueryWrapper);

        List<CollegeAdmins> collegeAdminsPageRecords = collegeAdminsPage.getRecords();
        List<PersonVo> personVoList = collegeAdminsPageRecords.stream().map(collegeAdmins -> {
            PersonVo personVo = new PersonVo();
            personVo.setId(collegeAdmins.getId());
            personVo.setUsername(collegeAdmins.getUsername());
            personVo.setNickname(collegeAdmins.getNickname());
            personVo.setPic(collegeAdmins.getPic());
            personVo.setPhone(collegeAdmins.getPhone());
            personVo.setEmail(collegeAdmins.getEmail());
            personVo.setStatus(MyConstants.USER_STATUS.get(collegeAdmins.getStatus()));
            personVo.setCreateTime(collegeAdmins.getCreateTime());
            personVo.setType(0);
            return personVo;
        }).collect(Collectors.toList());


        pageVo.setData(personVoList);
        pageVo.setPageCount(collegeAdminsPage.getPages());
        pageVo.setSize(pageSize);
        pageVo.setTotal(collegeAdminsPage.getTotal());
        pageVo.setCurrent(currentPage);

        return Result.okWithData(pageVo);
    }

    /**
     * 添加管理员
     *
     * @param personPo 管理员信息
     * @return 反馈
     */
    @Override
    @Transactional
    public Result<String> addCollegeAdmin(PersonPo personPo) {
        CollegeAdmins collegeAdmins = new CollegeAdmins();
        collegeAdmins.setUsername(personPo.getUsername());
        collegeAdmins.setPassword(BcryptUtil.hashPassword(personPo.getPassword()));
        collegeAdmins.setNickname(personPo.getNickname());
        collegeAdmins.setPhone(personPo.getPhone());
        collegeAdmins.setEmail(personPo.getEmail());
        collegeAdmins.setCreateTime(new Date());
        collegeAdmins.setUpdateTime(new Date());
        collegeAdmins.setStatus(1);
        collegeAdmins.setPic(personPo.getPic());

        save(collegeAdmins);

        SchoolCollageAdminRelations schoolCollageAdminRelations = new SchoolCollageAdminRelations();
        schoolCollageAdminRelations.setSchId(personPo.getSchoolId());
        schoolCollageAdminRelations.setColAdminId(collegeAdmins.getId());
        schoolCollageAdminRelationsService.save(schoolCollageAdminRelations);

        return Result.okWithData("增加成功");
    }

    /**
     * 获取学校中空闲的学院管理员列表
     * @param schoolId 学校id
     * @return 信息
     */
    @Override
    public Result<List<CollegeRestAdminVo>> getRestCollegeAdminList(Integer schoolId) {
        LambdaQueryWrapper<SchoolCollageAdminRelations> schoolCollageAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolCollageAdminRelationsLambdaQueryWrapper.eq(SchoolCollageAdminRelations::getSchId, schoolId);
        List<SchoolCollageAdminRelations> schoolCollageAdminRelationsList = schoolCollageAdminRelationsService.list(schoolCollageAdminRelationsLambdaQueryWrapper);
        List<CollegeRestAdminVo> collegeRestAdminVoList = new ArrayList<>();
        if(!schoolCollageAdminRelationsList.isEmpty()){

            List<Integer> collectIdList = schoolCollageAdminRelationsList.stream().map(SchoolCollageAdminRelations::getColAdminId).collect(Collectors.toList());
            List<Integer> collectNotIdList = collageAdminRelationsService.list().stream().map(CollageAdminRelations::getColAdminId).collect(Collectors.toList());

            LambdaQueryWrapper<CollegeAdmins> collegeAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            collegeAdminsLambdaQueryWrapper.in(CollegeAdmins::getId, collectIdList); //指定学校
            collegeAdminsLambdaQueryWrapper.notIn(!collectNotIdList.isEmpty(),CollegeAdmins::getId,collectNotIdList); //未管理学院

            List<CollegeAdmins> collegeAdminsList = list(collegeAdminsLambdaQueryWrapper);

            collegeRestAdminVoList = collegeAdminsList.stream().map(collegeAdmins -> {
                CollegeRestAdminVo collegeRestAdminVo = new CollegeRestAdminVo();
                collegeRestAdminVo.setId(collegeAdmins.getId());
                collegeRestAdminVo.setUsername(collegeAdmins.getUsername());
                collegeRestAdminVo.setNickname(collegeAdmins.getNickname());
                return collegeRestAdminVo;
            }).collect(Collectors.toList());
        }

        return Result.okWithData(collegeRestAdminVoList);
    }

    /**
     * 登录
     *
     * @param colAdminLoginPo 登录参数
     * @return 登录成功返回token，失败返回错误信息
     */
    @Override
    public Result<ColAdminLoginVo> doLogin(ColAdminLoginPo colAdminLoginPo) {
        String password = colAdminLoginPo.getPassword();
        String username = colAdminLoginPo.getUsername();

        LambdaQueryWrapper<CollegeAdmins> collegeAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        collegeAdminsLambdaQueryWrapper.eq(CollegeAdmins::getUsername, username);
        CollegeAdmins collegeAdminsFromDB = getOne(collegeAdminsLambdaQueryWrapper);

        if (collegeAdminsFromDB == null) {
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.USERNAME_ERROR);
        }

        if (!(BcryptUtil.checkPassword(password,collegeAdminsFromDB.getPassword()))){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PASSWORD_ERROR);
        }

        if (!schoolSetsService.sureHasSet(MyConstants.COLLEGE_ROLE,collegeAdminsFromDB.getId())) {
            throw new MyException(ResultCode.SUCCESS.getCode(),ResultCode.NOTOPEANSET.getMessage());
        }

        ColAdminLoginVo colAdminLoginVo = new ColAdminLoginVo();
        colAdminLoginVo.setId(collegeAdminsFromDB.getId());
        colAdminLoginVo.setUsername(collegeAdminsFromDB.getUsername());
        colAdminLoginVo.setNickname(collegeAdminsFromDB.getNickname());
        colAdminLoginVo.setPic(collegeAdminsFromDB.getPic());
        colAdminLoginVo.setToken(TokenUtils.generateToken(collegeAdminsFromDB.getId()));

        LambdaQueryWrapper<CollageAdminRelations> collageAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        collageAdminRelationsLambdaQueryWrapper.eq(CollageAdminRelations::getColAdminId, collegeAdminsFromDB.getId());

        CollageAdminRelations collegeAdminRelationsFromDB = collageAdminRelationsService.getOne(collageAdminRelationsLambdaQueryWrapper);

        if(collegeAdminRelationsFromDB != null){
            colAdminLoginVo.setCollegeId(collegeAdminRelationsFromDB.getColId());
        }

        return Result.okWithData(colAdminLoginVo);
    }
}




